<template>
  <el-dialog width="400" :title="dialogTitle" v-model="dialogVisible" modal draggable @close="closeDialog"
    :close-on-click-modal="false">
    <el-form class="dialog-form" :model="formData" ref="vForm" label-position="right" label-width="80px" size="medium"
      @submit.native.prevent :rules="formRules" :disabled="formDisabled">
      <el-form-item label="库房名称" prop="repositoryName">
        <el-input v-model="formData.repositoryName" placeholder="请输入库房名称" link maxlength="90" show-word-limit clearable>
        </el-input>
      </el-form-item>
      <el-form-item label="面积(㎡)" prop="repositoryArea">
        <el-input type="number" placeholder="请输入面积" v-model="formData.repositoryArea" @input="handleInput"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="repositoryAddress">
        <el-input v-model="formData.repositoryAddress" placeholder="请输入地址" link maxlength="85" show-word-limit
          clearable>
        </el-input>
      </el-form-item>
      <!--      <el-form-item label="平面图">-->
      <!--        <el-upload-->
      <!--          ref="uploads"-->
      <!--          class="upload-demo"-->
      <!--          :action="uploadURL + 'sys/image/uploadImage'"-->
      <!--          :data="{ path: 'repository' }"-->
      <!--          :multiple="false"-->
      <!--          :file-list="fileList"-->
      <!--          :headers="headers"-->
      <!--          :limit="1"-->
      <!--          accept=".jpg, .png, .jpeg"-->
      <!--          :show-file-list="true"-->
      <!--          :on-success="onSuccess"-->
      <!--          :on-progres="handleprogres"-->
      <!--          :on-preview="onPreview"-->
      <!--          :on-exceed="handleExceed"-->
      <!--        >-->
      <!--          <el-button size="small" type="primary">点击上传</el-button>-->
      <!--          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>-->
      <!--        </el-upload>-->
      <!--      </el-form-item>-->
      <el-form-item label="备注" prop="note">
        <el-input v-model="formData.note" placeholder="请输入备注" :rows="3" type="textarea" maxlength="255" show-word-limit
          clearable>
        </el-input>
      </el-form-item>
    </el-form>
    <div v-if="!formDisabled" slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, update, getInfo, getImage } from '@/api/bas/repository'
export default {
  name: 'repositoryDialog',
  data() {
    return {
      headers: {
        'X-Access-Token': localStorage.getItem('X-Access-Token'),
      },
      type: '',
      dialogTitle: '',
      dialogVisible: false,
      formData: {},
      formDisabled: false,
      formRules: {
        repositoryName: [{ required: true, message: '请输入库房名称', trigger: 'blur' }],
        repositoryArea: [{ required: true, message: '请输入面积(㎡)', trigger: 'blur' }],
      },
      fileList: [],
    }
  },
  methods: {
    handleInput(value) {
      if (value !== '') {
        const totalLength = 10 // 总长度（整数八位 + 小数两位）
        const decimalPrecision = 2 // 小数部分精度
        const minValue = '0.01' // 最小值
        // 获取小数点位置
        const decimalPointIndex = value.indexOf('.')
        // 判断并限制整数部分长度
        if (decimalPointIndex === -1) {
          // 无小数点，直接截取前八位整数
          this.formData.repositoryArea = value.slice(0, 8)
        } else if (decimalPointIndex > totalLength - decimalPrecision) {
          // 小数点位置过靠后，截取前totalLength - decimalPrecision位
          this.formData.repositoryArea = value.slice(0, totalLength - decimalPrecision)
        } else {
          // 小数点位置合适，截取整数部分和小数点后decimalPrecision位
          this.formData.repositoryArea = value.slice(0, decimalPointIndex + decimalPrecision + 1)
        }
        // 判断并设置最小值
        if (parseFloat(this.formData.repositoryArea) < parseFloat(minValue)) {
          this.formData.repositoryArea = minValue
        }
      }
    },
    // 上传成功后
    onSuccess(e, file, fileList) {
      if (e.code == 200) {
        this.formData.repositoryPlan = e.data
        this.formData.fileName = file.name
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败' + e.message)
      }
    },
    // 文件上传中的钩子
    handleprogres() {
      this.$message({
        message: '正在上传中',
      })
      return
    },
    handleExceed(files, fileList) {
      // 当文件数量超过限制时，触发此函数
      this.$message.warning('超出文件数量限制')
    },
    onPreview(file) {
      var param = {
        path: 'repository',
        url: file.response.data,
      }
      getImage(param)
        .then((res) => {
          if (res.data.code == 200) {
            var imgFile = this.base64ImgtoFile(res.data.data)
            this.downloadBlob(imgFile, file.name)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    base64ImgtoFile(dataurl, filename = 'file') {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      })
    },
    //图片下载
    downloadBlob(blob, filename) {
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = filename
      a.click()
      URL.revokeObjectURL(url)
    },
    add() {
      this.formDisabled = false
      this.type = 'add'
      this.dialogTitle = '添加库房'
      // 先清空表单数据
      this.formData = {}
      this.dialogVisible = true
    },
    edit(row) {
      this.formDisabled = false
      this.type = 'edit'
      this.dialogTitle = '编辑库房'
      getInfo(row.repositoryId)
        .then((res) => {
          if (res.data.code === 200) {
            this.formData = res.data.data
            // if (this.formData.repositoryPlan) {
            //   this.fileList = [
            //     { name: this.formData.fileName, response: { data: this.formData.repositoryPlan } },
            //   ]
            // }
            this.dialogVisible = true
          } else {
            this.$message.error(res.data.message)
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    submitForm() {
      this.$refs['vForm'].validate((valid) => {
        if (valid) {
          if (this.type === 'add') {
            add(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('添加成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          } else {
            update(this.formData)
              .then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('修改成功')
                  this.closeDialog()
                  this.$emit('ok')
                } else {
                  this.$message.warning(res.data.message)
                }
              })
              .catch((err) => {
                this.$message.error(err)
              })
          }
        }
      })
    },
    closeDialog() {
      this.fileList = []
      // this.$refs.uploads.clearFiles()
      this.$refs['vForm'].resetFields()
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped>
.dialog-form {
  padding: 0 30px;
  /* 根据需求调整数值 */
}

.upload-demo {
  /* margin: 0 0 0 15px; */
  display: inline-block;
}
</style>
